<template>
	<view class="container">
		<scroll-view scroll-y class="demo-scroll">
			<!-- 头部信息 -->
			<view class="header">
				<text class="title">wht-request Demo</text>
				<text class="subtitle">一个功能强大的 UniApp 请求插件</text>
			</view>

			<!-- 基础请求示例 -->
			<view class="section">
				<view class="section-title">基础请求示例</view>
				<view class="card-grid">
					<!-- GET 请求 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">GET 请求</text>
							<text class="card-subtitle">获取用户信息</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleBasicGet">发起请求</button>
							<view class="result-box" v-if="getResult">
								<text class="result-label">响应结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(getResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>

					<!-- POST 请求 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">POST 请求</text>
							<text class="card-subtitle">创建新用户</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleBasicPost">发起请求</button>
							<view class="result-box" v-if="postResult">
								<text class="result-label">响应结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(postResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 拦截器示例 -->
			<view class="section">
				<view class="section-title">拦截器示例</view>
				<view class="card-grid">
					<!-- 请求拦截器 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">请求拦截器</text>
							<text class="card-subtitle">自动添加认证信息</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleRequestInterceptor">测试拦截器</button>
							<view class="result-box" v-if="interceptorResult">
								<text class="result-label">响应结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(interceptorResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>

					<!-- 响应拦截器 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">响应拦截器</text>
							<text class="card-subtitle">自动处理响应数据</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleResponseInterceptor">测试拦截器</button>
							<view class="result-box" v-if="responseInterceptorResult">
								<text class="result-label">响应结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(responseInterceptorResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 高级功能示例 -->
			<view class="section">
				<view class="section-title">高级功能示例</view>
				<view class="card-grid">
					<!-- 文件上传 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">文件上传</text>
							<text class="card-subtitle">支持进度回调</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleUpload">选择文件上传</button>
							<view class="progress-bar" v-if="uploadProgress > 0">
								<view class="progress-inner" :style="{width: uploadProgress + '%'}">
									<text class="progress-text">{{uploadProgress}}%</text>
								</view>
							</view>
							<view class="result-box" v-if="uploadResult">
								<text class="result-label">上传结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(uploadResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>

					<!-- 文件下载 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">文件下载</text>
							<text class="card-subtitle">支持进度回调</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleDownload">开始下载</button>
							<view class="progress-bar" v-if="downloadProgress > 0">
								<view class="progress-inner" :style="{width: downloadProgress + '%'}">
									<text class="progress-text">{{downloadProgress}}%</text>
								</view>
							</view>
							<view class="result-box" v-if="downloadResult">
								<text class="result-label">下载结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(downloadResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 任务管理示例 -->
			<view class="section">
				<view class="section-title">任务管理示例</view>
				<view class="card-grid">
					<!-- 取消请求 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">取消请求</text>
							<text class="card-subtitle">支持取消单个请求</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleCancelRequest">发起可取消请求</button>
							<button class="btn btn-warning" @click="cancelRequest" v-if="canCancel">取消请求</button>
							<view class="result-box" v-if="cancelResult">
								<text class="result-label">请求结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(cancelResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>

					<!-- 并发请求 -->
					<view class="card">
						<view class="card-header">
							<text class="card-title">并发请求</text>
							<text class="card-subtitle">同时发起多个请求</text>
						</view>
						<view class="card-content">
							<button class="btn" @click="handleConcurrent">发起并发请求</button>
							<view class="result-box" v-if="concurrentResult">
								<text class="result-label">请求结果：</text>
								<scroll-view class="result-scroll" scroll-y>
									<text class="result-text">{{JSON.stringify(concurrentResult, null, 2)}}</text>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 自定义实例示例 -->
			<view class="section">
				<view class="section-title">自定义实例示例</view>
				<view class="card">
					<view class="card-header">
						<text class="card-title">创建自定义实例</text>
						<text class="card-subtitle">独立配置和拦截器</text>
					</view>
					<view class="card-content">
						<button class="btn" @click="handleCustomInstance">使用自定义实例</button>
						<view class="result-box" v-if="customInstanceResult">
							<text class="result-label">请求结果：</text>
							<scroll-view class="result-scroll" scroll-y>
								<text class="result-text">{{JSON.stringify(customInstanceResult, null, 2)}}</text>
							</scroll-view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import WhtRequest from '@/uni_modules/wht-request/js_sdk/index.js'

export default {
	data() {
		return {
			// 基础请求结果
			getResult: null,
			postResult: null,
			
			// 拦截器结果
			interceptorResult: null,
			responseInterceptorResult: null,
			
			// 文件上传/下载
			uploadProgress: 0,
			uploadResult: null,
			downloadProgress: 0,
			downloadResult: null,
			
			// 任务管理
			cancelResult: null,
			canCancel: false,
			currentRequestUrl: null,
			concurrentResult: null,
			
			// 自定义实例
			customInstanceResult: null,
			
			// 自定义请求实例
			customRequest: null
		}
	},
	created() {
		// 创建自定义请求实例
		this.customRequest = WhtRequest.create({
			baseURL: 'https://api.example.com',
			timeout: 5000,
			validateStatus: (status) => status === 200,
			header: {
				'Custom-Instance': 'true'
			}
		})
	},
	methods: {
		// 基础GET请求
		async handleBasicGet() {
			console.log('发起 GET 请求')
			try {
				const res = await this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/1')
				console.log('GET 请求成功:', res.data)
				this.getResult = res.data
			} catch (error) {
				console.error('GET 请求失败:', error)
				this.getResult = error
			}
		},

		// 基础POST请求
		async handleBasicPost() {
			const data = {
				name: 'Test User',
				email: 'test@example.com'
			}
			console.log('发起 POST 请求:', data)
			try {
				const res = await this.$whtRequest.post('https://jsonplaceholder.typicode.com/users', data)
				console.log('POST 请求成功:', res.data)
				this.postResult = res.data
			} catch (error) {
				console.error('POST 请求失败:', error)
				this.postResult = error
			}
		},

		// 请求拦截器示例
		handleRequestInterceptor() {
			// 添加请求拦截器
			const removeInterceptor = this.$whtRequest.addRequestInterceptor(
				(config) => {
					console.log('请求拦截器:', config)
					config.header['Authorization'] = 'Bearer test_token'
					return config
				},
				(error) => {
					console.error('请求拦截器错误:', error)
					return Promise.reject(error)
				}
			)

			// 发起请求
			this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/1')
				.then(res => {
					console.log('请求成功:', res.data)
					this.interceptorResult = res.data
					// 请求完成后移除拦截器
					removeInterceptor()
				})
				.catch(error => {
					console.error('请求失败:', error)
					this.interceptorResult = error
					removeInterceptor()
				})
		},

		// 响应拦截器示例
		handleResponseInterceptor() {
			// 添加响应拦截器
			const removeInterceptor = this.$whtRequest.addResponseInterceptor(
				(response) => {
					console.log('响应拦截器:', response)
					// 修改响应数据
					if (response.data) {
						response.data.intercepted = true
						response.data.timestamp = new Date().toISOString()
					}
					return response
				},
				(error) => {
					console.error('响应拦截器错误:', error)
					return Promise.reject(error)
				}
			)

			// 发起请求
			this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/1')
				.then(res => {
					console.log('请求成功:', res.data)
					this.responseInterceptorResult = res.data
					removeInterceptor()
				})
				.catch(error => {
					console.error('请求失败:', error)
					this.responseInterceptorResult = error
					removeInterceptor()
				})
		},

		// 文件上传示例
		async handleUpload() {
			// 选择文件
			uni.chooseImage({
				count: 1,
				success: async (chooseImageRes) => {
					const tempFilePath = chooseImageRes.tempFilePaths[0]
					
					try {
						const res = await this.$whtRequest.upload({
							url: 'http://localhost:8082/api/files/upload',
							filePath: tempFilePath,
							name: 'file',
							
							onUploadProgress: (progressEvent) => {
								this.uploadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100)
							}
						})
						console.log('上传成功:', res)
						this.uploadResult = res.data
					} catch (error) {
						console.error('上传失败:', error)
						this.uploadResult = error
					}
				}
			})
		},

		// 文件下载示例
		async handleDownload() {
			try {
				const res = await this.$whtRequest.download({
					url: 'http://localhost:8082/uploads/2024/12/09/1733725620407.png',
					onDownloadProgress: (progressEvent) => {
						this.downloadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100)
					}
				})
				console.log('下载成功:', res)
				this.downloadResult = res
			} catch (error) {
				console.error('下载失败:', error)
				this.downloadResult = error
			}
		},

		// 发起可取消的请求
		handleCancelRequest() {
			this.canCancel = true
			this.currentRequestUrl = 'https://jsonplaceholder.typicode.com/users'
			
			this.$whtRequest.get(this.currentRequestUrl)
				.then(res => {
					console.log('请求成功:', res.data)
					this.cancelResult = res.data
				})
				.catch(error => {
					console.error('请求失败或被取消:', error)
					this.cancelResult = error
				})
				.finally(() => {
					this.canCancel = false
					this.currentRequestUrl = null
				})
		},

		// 取消请求
		cancelRequest() {
			if (this.currentRequestUrl) {
				this.$whtRequest.abort(this.currentRequestUrl)
				this.canCancel = false
			}
		},

		// 并发请求示例
		async handleConcurrent() {
			try {
				const requests = [
					this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/1'),
					this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/2'),
					this.$whtRequest.get('https://jsonplaceholder.typicode.com/users/3')
				]
				
				console.log('发起并发请求')
				const results = await Promise.all(requests)
				console.log('并发请求完成:', results)
				this.concurrentResult = results.map(res => res.data)
			} catch (error) {
				console.error('并发请求失败:', error)
				this.concurrentResult = error
			}
		},

		// 使用自定义实例
		async handleCustomInstance() {
			try {
				const res = await this.customRequest.get('/custom-endpoint')
				console.log('自定义实例请求成功:', res.data)
				this.customInstanceResult = res.data
			} catch (error) {
				console.error('自定义实例请求失败:', error)
				this.customInstanceResult = error
			}
		}
	}
}
</script>

<style>
.container {
	padding: 30rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.demo-scroll {
	height: calc(100vh - 60rpx);
}

.header {
	text-align: center;
	margin-bottom: 40rpx;
}

.title {
	font-size: 48rpx;
	font-weight: bold;
	color: #2c3e50;
	margin-bottom: 10rpx;
}

.subtitle {
	font-size: 28rpx;
	color: #7f8c8d;
}

.section {
	margin-bottom: 40rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #34495e;
	margin-bottom: 20rpx;
	padding-left: 20rpx;
	border-left: 8rpx solid #3498db;
}

.card-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
	gap: 20rpx;
}

.card {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.3s ease;
}

.card:hover {
	transform: translateY(-2rpx);
}

.card-header {
	margin-bottom: 20rpx;
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
}

.card-subtitle {
	font-size: 24rpx;
	color: #95a5a6;
	margin-top: 4rpx;
}

.btn {
	background: #3498db;
	color: #ffffff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx 30rpx;
	font-size: 28rpx;
	margin-bottom: 20rpx;
	transition: background 0.3s ease;
}

.btn:hover {
	background: #2980b9;
}

.btn-warning {
	background: #e74c3c;
}

.btn-warning:hover {
	background: #c0392b;
}

.result-box {
	background: #f8f9fa;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-top: 20rpx;
}

.result-label {
	font-size: 24rpx;
	color: #7f8c8d;
	margin-bottom: 10rpx;
	display: block;
}

.result-scroll {
	max-height: 300rpx;
}

.result-text {
	font-family: monospace;
	font-size: 24rpx;
	color: #2c3e50;
	white-space: pre-wrap;
	word-break: break-all;
}

.progress-bar {
	background: #ecf0f1;
	border-radius: 100rpx;
	height: 30rpx;
	margin: 20rpx 0;
	overflow: hidden;
}

.progress-inner {
	background: #2ecc71;
	height: 100%;
	border-radius: 100rpx;
	transition: width 0.3s ease;
	position: relative;
}

.progress-text {
	position: absolute;
	right: 10rpx;
	color: #ffffff;
	font-size: 20rpx;
	line-height: 30rpx;
}
</style>
